/*
 * @lc app=leetcode.cn id=142 lang=cpp
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode *detectCycle(ListNode *head)
    {
        //环形链表2 找到环的起点
        //首先找到第一次相遇的位置
        ListNode *dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode *fast = dummyHead;
        ListNode *slow = dummyHead;
        while (fast != slow)
        {
            if (fast->next == NULL || fast->next->next == NULL)
            {
                return NULL;
            }
else
        }

        int len = 0; //环的长度
        do
        {
            fast = fast->next->next;
            slow = slow->next;
            len++;
        } while (slow != fast);
        fast = dummyHead;
        slow = dummyHead;
        while (len--)
        {
            fast = fast->next;
        }
        while (fast != slow)
        {
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
};
// @lc code=end
